package cn.pzhu.pserson.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.pzhu.pserson.model.Lipin;
import cn.pzhu.pserson.model.Userinfo;
import cn.pzhu.pserson.service.*;
import cn.pzhu.pserson.util.ExcelFormatUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import cn.pzhu.pserson.util.ResponseUtil;
import cn.pzhu.pserson.dto.PrizeDTO;
import cn.pzhu.pserson.dto.LimitShowDTO;
import cn.pzhu.pserson.model.Prize;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/prize")
public class PrizeController {
    private  final  static Logger logger = LoggerFactory.getLogger(LogoController.class);
    @Autowired
    private IPrizeService prizeService;

    @Autowired
    private IUserinfoService userinfoService;

    @Autowired
    private ILipinService lipinService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    private IAppointmentService appointmentService;

    @CrossOrigin
    @RequestMapping(value = "/getList", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> getList(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        String ip = request.getParameter("uuid");
        if(ip == null || "".equals(ip) || "null".equals(ip)){
//            return ResponseUtil.getResEntityForGet(ResponseUtil.FAIL_RS)
            ip = getIpAddr(request);
        }

//        List<Map<String, Object>> prizes  = prizeService.loadMaps("ip=?", new String[]{ip}, null,null,0,1);
        List<Map<String, Object>> prizes  = prizeService.getDataByDateTime(ip);
        result.put("list", prizes);
        return ResponseUtil.getResEntityForGetAndJson(result);
    }

    @CrossOrigin
    @RequestMapping(value = "/getByAttr2", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> getByAttr2(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        String ip = request.getParameter("uuid");
        if(ip == null || "".equals(ip) || "null".equals(ip)){
//            return ResponseUtil.getResEntityForGet(ResponseUtil.FAIL_RS)
            ip = getIpAddr(request);
        }
        String attr2 = request.getParameter("attr2");

        List<Map<String, Object>> prizes  = prizeService.loadMaps("attr2=?", new String[]{attr2}, null,null,0,1);

        result.put("msg", prizes.get(0));
        return ResponseUtil.getResEntityForGetAndJson(result);
    }


    @CrossOrigin
    @RequestMapping(value = "/receive", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> receive(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();

        String ip = request.getParameter("uuid");

        String attr3 = request.getParameter("attr2");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        List<Prize> prizes  = prizeService.loadModels("attr2=?", new String[]{attr3}, null,null,0,1);

        Prize prizeModel = prizes.get(0);
        prizeModel.setUsername(name);
        prizeModel.setPhone(phone);
        prizeModel.setIsget(1);

        //先判断还有没有礼品
//        Integer id =  Integer.parseInt(prizeModel.getAttr1());
//        List<Lipin> lipins =  lipinService.loadModels("id=?", new Integer[]{id}, null,null,0,1);
//
//        Lipin lipin = lipins.get(0);
//        Integer surnum = lipin.getSurnum();
//        if(surnum > 0){
//            surnum = surnum - 1;
//            lipin.setSurnum(surnum);
//            lipinService.update(lipin);
//        }else{
//            result.put("message", "对不起，该礼品已经领完了，请下次参与！");
//            return ResponseUtil.getResEntityForGetAndJson(result);
//        }

        Boolean bool = prizeService.update(prizeModel);
        return ResponseUtil.getResEntityForGet(bool);

    }

    @CrossOrigin
    @RequestMapping(value = "/saveCode", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> saveCode(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();

        String ip = request.getParameter("uuid");
        if(ip == null || "".equals(ip) || "null".equals(ip)){
//            return ResponseUtil.getResEntityForGet(ResponseUtil.FAIL_RS)
            ip = getIpAddr(request);
        }

        String attr2 = request.getParameter("attr2");
        String code = request.getParameter("code");

        long count =  codeService.count(null, "code=?", new String[]{code},false);

        if(count > 0){
            List<Prize> prizes  = prizeService.loadModels("attr2=?", new String[]{attr2}, null,null,0,1);

            if(prizes.get(0) != null){
                Integer lipinid = Integer.parseInt(prizes.get(0).getAttr1() + "");
                Lipin lipin = lipinService.findModel(lipinid);

                Integer surnum = lipin.getSurnum();
                if(surnum > 0){
                    surnum = surnum - 1;
                    lipin.setSurnum(surnum);

                    lipinService.update(lipin);

                    Prize prize = prizes.get(0);
                    prize.setIscode(1);
                    prizeService.update(prize);

                    result.put("state", true);
                }else{
                    result.put("message", "礼品数量不足，不能领取！");
                }

            }else{
                return ResponseUtil.getResEntityForGet(ResponseUtil.FAIL_RS);
            }
        }else{
            result.put("message", "核销码不正确！");
        }

        return ResponseUtil.getResEntityForGetAndJson(result);

    }


    @CrossOrigin
    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<String> save(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();

        String ip = request.getParameter("uuid");

        if(ip != null) {
            List<Userinfo> userinfos = userinfoService.loadModels("ip=?", new String[]{ip}, null, null, 0, 1);
            Userinfo userinfo = userinfos.get(0);
            Integer count = userinfo.getCount();
            if (count <= 0) {
                result.put("message", "当前用户的抽奖机会已经用完无法继续抽奖！");
                return ResponseUtil.getResEntityForGetAndJson(result);
            }

            long summany_prize_count = prizeService.count("ip=?",new String[]{ip});
            if(summany_prize_count >= 15){
                result.put("message", "每个用户最多只能抽取15次，您已满15次不能再抽奖了！");
                return ResponseUtil.getResEntityForGetAndJson(result);
            }

            long prize_count = prizeService.count("ip=? and to_days(createtime) = to_days(now())" , new String[]{ip});
            if(prize_count >= 5){
                result.put("message", "当前用户的抽奖机会已经用完无法继续抽奖！");
                return ResponseUtil.getResEntityForGetAndJson(result);
            }

            List<Map<String, Object>> list = lipinService.getDataByDateTime();

            long isp =  prizeService.count("ip=? and (attr4='一等奖' or attr4='二等奖')",new String[]{ip});

            List<Map<String, Object>> model = new ArrayList<>();
            for(int i = 0;i<list.size();i++){

                if(new Double(list.get(i).get("synum").toString()).intValue() > 0){
                    Map<String,Object> maps = new HashMap<>();
                    maps.put("name",list.get(i).get("name"));
                    maps.put("key",list.get(i).get("id"));
                    maps.put("synum",list.get(i).get("synum"));
                    maps.put("level",list.get(i).get("level"));
                    maps.put("levelname",getLevelTitle(Integer.parseInt(list.get(i).get("level") + "")));
                    model.add(maps);
                }

            }



            List<Map<String, Object>> list1 = Draw(model, isp, ip);


            if(list1.size() <= 0){
                result.put("message", "礼物库存不足！");
                return ResponseUtil.getResEntityForGetAndJson(result);
            }

            int max=list1.size();
            int min=0;
            Random random = new Random();

            int s = random.nextInt(max)%(max-min+1) + min;


            Map<String, Object> map = list1.get(s);

            String prize_name = map.get("name").toString();
//            request.getParameter("prize_name");
            String prize_levelname = map.get("levelname").toString();
//                    request.getParameter("prize_levelname");
            Integer prize_value = Integer.parseInt(map.get("value") + "");
//                    Integer.parseInt(request.getParameter("prize_id"));


            count = count - 1;
            userinfo.setCount(count);
            Boolean flag1 = userinfoService.update(userinfo);

            if (prize_value == 0) {
                return ResponseUtil.getResEntityForPPP(false);
            }

            Prize prize = new Prize();
            prize.setIp(ip);
            prize.setPrizename(prize_name);
            prize.setAttr1(prize_value + "");
            prize.setAttr4(prize_levelname);
            prize.setIsget(0);
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            prize.setAttr3(f.format(new Date()));
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            prize.setAttr2(uuid);
            prize.setIscode(0);
            prize.setCreatetime(new Date());

            Boolean flag = prizeService.save(prize);
            if (flag) {
                result.put("prize", prize);
                return ResponseUtil.getResEntityForGetAndJson(result);
            }
        }

        return ResponseUtil.getResEntityForPPP(false);
    }

    private List<Map<String, Object>> Draw(List<Map<String, Object>> model, long isp, String opneid){
        List<Map<String, Object>>  prizeList = new ArrayList<>();//按照权重分解后的奖品数组

        for(int i=0; i<model.size(); i++ ){
            Integer count = Integer.parseInt(model.get(i).get("synum") + "");
            if(isp<=0 && Integer.parseInt(model.get(i).get("level") + "") <=1){
                Integer level1Count = (count / 10);
                for (int j = 0; j < level1Count; j++) {
                    prizeList.add(addItem(model.get(i)));
                }

                long cs= appointmentService.count("openid=?",new String[]{opneid});
                if(cs > 0){
                    for (int j = 0; j < level1Count; j++) {
                        prizeList.add(addItem(model.get(i)));
                    }
                }

            }else if( Integer.parseInt(model.get(i).get("level").toString()) > 1){
                for (int j = 0; j < count; j++) {
                    prizeList.add(addItem(model.get(i)));
                }
            }
        }

        Collections.shuffle(prizeList);
        return  prizeList;
    }


    private Map<String, Object> addItem(Map<String, Object> it){
        Map<String, Object> item = new HashMap<>();
        item.put("name", it.get("name"));
        item.put("value", it.get("key"));
        item.put("level", it.get("level"));
        item.put("levelname", it.get("levelname"));

        return item;
    }


    private String getLevelTitle (Integer param) {
        String result = "";
        switch (param){
            case 0:
                result =  "特等奖";
                break;
            case 1:
                result =  "一等奖";
                break;
            case 2:
                result =  "二等奖";
                break;
            case 3:
                result =  "三等奖";
                break;
            case 4:
                result =  "幸运奖";
                break;
        }

        return result;
    }

    public String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    @CrossOrigin
    @RequestMapping(value = "/export", method = RequestMethod.GET, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<byte[]> export(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) throws ParseException {


        List<Map<String,Object>>  prizeGroupList = prizeService.getByGroupByNew(-1, -1);

        List<Prize> prizes = new ArrayList<>();
        for(int i = 0;i< prizeGroupList.size(); i++){
            Prize prize = new Prize();
            Map<String,Object> item = prizeGroupList.get(i);
            prize.setUsername(item.get("name").toString());
            prize.setPhone(item.get("uphone").toString());
            prize.setAttr4(item.get("attr4").toString());
            prize.setPrizename(item.get("prizename").toString());
            prize.setIscode(Integer.parseInt(item.get("iscode")+""));
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            prize.setCreatetime(formatter.parse(formatter.format(item.get("createtime"))));
            prizes.add(prize);
        }


        try {
            return buildResponseEntity(export(prizes), "已录入领奖记录表-燕园理想城.xls");
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>导出excel 异常，原因为：" + e.getMessage());
        }
        return null;
    }

    @CrossOrigin
    @RequestMapping(value = "/exportAll", method = RequestMethod.GET, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<byte[]> exportAll(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) {
        List<Prize> prizeList = prizeService.loadModels(null, new String[]{}, null, null, -1, -1);

        try {
            return buildResponseEntity(export(prizeList), "全部中奖记录表-燕园理想城.xls");
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>导出excel 异常，原因为：" + e.getMessage());
        }
        return null;
    }

    public ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>开始下载文件>>>>>>>>>>");
        if (this.logger.isDebugEnabled())
            this.logger.debug("download: " + name);
        HttpHeaders header = new HttpHeaders();
        String fileSuffix = name.substring(name.lastIndexOf('.') + 1);
        fileSuffix = fileSuffix.toLowerCase();

        Map<String, String> arguments = new HashMap<String, String>();
        arguments.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        arguments.put("xls", "application/vnd.ms-excel");

        String contentType = arguments.get(fileSuffix);
        header.add("Content-Type", (StringUtils.hasText(contentType) ? contentType : "application/x-download"));
        if(is!=null && is.available()!=0){
            header.add("Content-Length", String.valueOf(is.available()));
            header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
            byte[] bs = IOUtils.toByteArray(is);
            logger.info(">>>>>>>>>>>>>>>>>>>>结束下载文件-有记录>>>>>>>>>>");
            logger.info(">>>>>>>>>>结束导出excel>>>>>>>>>>");
            return new ResponseEntity<>(bs, header, HttpStatus.OK);
        }else{
            String string="数据为空";
            header.add("Content-Length", "0");
            header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
            logger.info(">>>>>>>>>>>>>>>>>>>>结束下载文件-无记录>>>>>>>>>>");
            logger.info(">>>>>>>>>>结束导出excel>>>>>>>>>>");
            return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);
        }
    }


    private InputStream export(List<Prize> list) {
        logger.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        // 每一列字段名
        String[] strs = new String[] { "姓名", "手机号", "中奖奖项", "中奖礼品", "是否核销", "录入时间"};

        // 字段名所在表格的宽度
        int[] ints = new int[] { 5000, 5000, 5000, 5000, 5000, 5000 };

        // 设置表头样式
        ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);
        logger.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

        if (list != null && list.size() > 0) {
            logger.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            for (int i = 0; i < list.size(); i++) {
                Prize user = list.get(i);
                SXSSFRow row = sheet.createRow(i + 1);
                int j = 0;

                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(user.getUsername());
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(user.getPhone() + "");
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(user.getAttr4());
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(user.getPrizename());
                cell.setCellStyle(content);


                cell = row.createCell(j++);
                cell.setCellValue(user.getIscode() == 1? "已核销": "未核销");
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cell.setCellValue(f.format(user.getCreatetime()));
                cell.setCellStyle(content);


            }
            logger.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null)
                        inputStream1.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(Model model,
                             @Validated
        LimitShowDTO limitShowDTO, BindingResult errors) {

//        List<Prize> prizeList = prizeService.loadModels(null, new String[]{}, null, null, limitShowDTO.getPageNum(), limitShowDTO.getPageSize());
        long count = prizeService.count();
        List<Map<String,Object>>  prizeGroupList = prizeService.getByGroupByNew(limitShowDTO.getPageNum(), limitShowDTO.getPageSize());

//        for(int i=0;i< prizeGroupList.size();i++){
//            Map<String,Object> map = new HashMap<>();
//            map.put("format_time", f.format(prizeGroupList.get(0).get("createtime")));
//           prizeGroupList.add(map);
//        }
//        result.put("total", count);

        model.addAttribute("size", count);
        model.addAttribute("list", prizeGroupList);
        model.addAttribute("pageNum", limitShowDTO.getPageNum());
        model.addAttribute("nums", Math.ceil(Double.parseDouble(count + "") / Double.parseDouble(limitShowDTO.getPageSize() + "")));
        return new ModelAndView("receive/list", (Map<String, ?>) model);
    }

    @RequestMapping(value = "/userlist", method = RequestMethod.GET)
    public ModelAndView userlist(Model model,
                             @Validated
                                     LimitShowDTO limitShowDTO, BindingResult errors) {

        Map<String, Object> result = new HashMap<String, Object>();

        List<Prize>  prizeGroupList = prizeService.getDataByGroup();

        List<Prize> resultPrize = new ArrayList<>();
        for(int n=0;n< prizeGroupList.size(); n++){
            if(prizeGroupList.get(n).getUsername() != null){
                resultPrize.add(prizeGroupList.get(n));
            }
        }

        model.addAttribute("size", resultPrize.size());
        model.addAttribute("list", resultPrize);
        model.addAttribute("pageNum", limitShowDTO.getPageNum());
        model.addAttribute("nums", Math.ceil(Double.parseDouble(prizeGroupList.size() + "") / Double.parseDouble(limitShowDTO.getPageSize() + "")));
        return new ModelAndView("userinfo/list", (Map<String, ?>) model);
    }

    @CrossOrigin
    @RequestMapping(value = "/exportUserinfo", method = RequestMethod.GET, produces = {"text/plain;charset=utf-8","text/html;charset=utf-8"}             )
    @ResponseBody
    public ResponseEntity<byte[]> exportUserinfo(
            @Validated
                    LimitShowDTO limitShowDTO, BindingResult errors, HttpServletResponse response, HttpServletRequest request) {

        Map<String, Object> result = new HashMap<String, Object>();

        List<Prize>  prizeGroupList = prizeService.getDataByGroup();

        List<Prize> resultPrize = new ArrayList<>();
        for(int n=0;n< prizeGroupList.size(); n++){
            if(prizeGroupList.get(n).getUsername() != null){
                resultPrize.add(prizeGroupList.get(n));
            }
        }

        try {
            return buildResponseEntity(exportUserInfo(resultPrize), "客户信息表-燕园理想城.xls");
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>导出excel 异常，原因为：" + e.getMessage());
        }
        return null;

    }

    private InputStream exportUserInfo(List<Prize> list) {
        logger.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream1 = null;
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
        CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

        // 每一列字段名
        String[] strs = new String[] { "姓名", "手机号", "录入时间"};

        // 字段名所在表格的宽度
        int[] ints = new int[] { 5000, 5000, 5000 };

        // 设置表头样式
        ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);
        logger.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

        if (list != null && list.size() > 0) {
            logger.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            for (int i = 0; i < list.size(); i++) {
                Prize user = list.get(i);
                SXSSFRow row = sheet.createRow(i + 1);
                int j = 0;

                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(user.getUsername());
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                cell.setCellValue(user.getPhone() + "");
                cell.setCellStyle(content);

                cell = row.createCell(j++);
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cell.setCellValue(f.format(user.getCreatetime()));
                cell.setCellStyle(content);

            }
            logger.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }
        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream1 = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream1 != null)
                        inputStream1.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return inputStream1;
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<String> show(@PathVariable("id") Integer id) {
        Map<String, Object> prizeModel = prizeService.findMap(id);

        return ResponseUtil.getResEntityForGetAndJson(prizeModel);
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> create(
        @Validated
        PrizeDTO prizeDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        Prize prizeModel = prizeDTO.toModel();

        return ResponseUtil.getResEntityForPPP(prizeService.save(prizeModel));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity<String> update(@PathVariable("id") Integer id,
        @Validated
        PrizeDTO prizeDTO, BindingResult errors) {

        Prize prizeModel = prizeDTO.toModel();
        prizeModel.setId(id);
        return ResponseUtil.getResEntityForPPP(prizeService.update(prizeModel));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> destory(@PathVariable("id") Integer id) {
        return ResponseUtil.getResEntityForDel(prizeService.delete(id));
    }

    @RequestMapping(value = "/deletes", method = RequestMethod.DELETE)
    public ResponseEntity<String> deletes(@RequestParam("primaryKeys") Integer[] primaryKeys) {
        return ResponseUtil.getResEntityForDel(prizeService.batchDelete(primaryKeys));
    }
}
